package com.techstar.ats.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.ChannelPipeline;
import org.springframework.stereotype.Component;
import com.techstar.ats.AtsProperties;
import com.techstar.ats.ConnectProperties;
import com.techstar.ats.netty.AtsNettyClient;
import com.techstar.ats.netty.handler.LiveHandler;
import com.techstar.ats.netty.handler.ScheduleHandler;

@Component
public class AtsChannelFactory {
	public final Map<Integer, ConnectProperties> properties = new HashMap<>();
	public final Map<Integer, AtsNettyClient> nettyBeans = new ConcurrentHashMap<>();
	private final LiveService liveService;

	public AtsChannelFactory(AtsProperties atsProperties, LiveService liveService) {
		List<ConnectProperties> connects = atsProperties.getConnects();
		connects.forEach(connect -> properties.put(connect.getLine(), connect));
		this.liveService = liveService;
	}

	public AtsNettyClient getNettyBean(int line) {
		return nettyBeans.computeIfAbsent(line, x -> {
			ConnectProperties connect = properties.get(x);
			if(connect.isLive()) {
				return new AtsNettyClient(connect) {
					protected void customHandler(ChannelPipeline pipeline) {
						pipeline.addLast(new LiveHandler(liveService));
					}
				};
			} else {
				return new AtsNettyClient(connect) {
					protected void customHandler(ChannelPipeline pipeline) {
						pipeline.addLast(new ScheduleHandler(null));
					}
				};
			}
		});
	}

	public void removeTerminated() {
		nettyBeans.entrySet()
			.removeIf(entry -> {
				AtsNettyClient client = entry.getValue();
				return !client.isRunning();
			});
	}
}
